/*
 * Created by JFormDesigner on Sat Aug 11 16:55:23 EDT 2007
 */

package org.timeticker.gui;

import java.util.*;
import org.timeticker.*;
import org.timeticker.impl.ActivityImpl;
import org.apache.log4j.Logger;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.*;

/**
 * @author Ivan Latysh
 */
public class ActivityDialog extends JDialog {

  /** Component logger */
  protected Logger logger = Logger.getLogger(this.getClass().getName());
  /** Activity */
  protected Activity activity;
  /** Date to Time formatter */
  protected SimpleDateFormat date2TimeFormat = new SimpleDateFormat("HH:mm");
  /** Time to Date formatter */
  protected SimpleDateFormat time2DateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
  /** Date formatter */
  protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-");
  /** Date this activity belong to */
  protected Date date;
  /** dialog result action */
  protected String action = "cancel";
  /** Work types drop down model */
  protected ObjectListComboBoxModel workTypesComboBoxModel;
  /** Project drop down model */
  protected ObjectListComboBoxModel projectsComboBoxModel;

  /**
   * Return activity
   *
   * @return activity
   */
  public Activity getActivity() {
    return activity;
  }

  /**
   * Return dialog result action
   * @return result action [<tt>save</tt>|<tt>cancel</tt>]
   */
  public String getAction() {
    return action;
  }

  /**
   * Create a new dialog
   *
   * @param owner dialog owner
   * @param activity activity or <tt>null</tt>
   */
  public ActivityDialog(Frame owner, Activity activity) {
		super(owner);
    this.activity = activity;
    preInit();
    initComponents();
    postInit();
  }

  /**
   * Create a new dialog
   *
   * @param owner dialog owner
   * @param activity activity or <tt>null</tt>
   */
	public ActivityDialog(Dialog owner, Activity activity) {
		super(owner);
    this.activity = activity;
    preInit();
    initComponents();
    postInit();
  }

  /**
   * Pre-Initialize dialog
   */
  protected void preInit() {
    // create WorkTypes drop down model
    ObjectList<WorkType> workTypes = Timekeeper.getInstance().getObjectList(Timekeeper.WORK_TYPE_LIST);
    workTypesComboBoxModel = new ObjectListComboBoxModel(workTypes);
    // create projects drop down model
    ObjectList<Project> projects = Timekeeper.getInstance().getObjectList(Timekeeper.PROJECT_LIST);
    projectsComboBoxModel = new ObjectListComboBoxModel(projects);
  }

  /**
   * Post-Initialize dialog
   */
  protected void postInit() {
    // set custom renderer
    workTypeCombo.setRenderer(new ObjectComboBoxRenderer("title"));
    projectCombo.setRenderer(new ObjectComboBoxRenderer("title"));

    // create activity if it is not given to us
    if (null==activity) activity = new ActivityImpl();
    // set current date
    date = activity.getStartTime(); 
    // set title
    title.setText(activity.getTitle());
    // set work type
    workTypeCombo.setSelectedItem(workTypesComboBoxModel.getObjects().get(activity.getWorkTypeCode()));
    // set project
    projectCombo.setSelectedItem(projectsComboBoxModel.getObjects().get(activity.getProjectCode()));
    // set start time
    startTime.setText(date2TimeFormat.format((null!=activity.getStartTime() ?activity.getStartTime() :new Date())));
    // set finish time
    finishTime.setText(null!=activity.getFinishTime() ? date2TimeFormat.format(activity.getFinishTime()) :"");
    // set comments
    comments.setText(activity.getComments());
  }

  private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Ivan Latysh
		ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");
		dialogPane = new JPanel();
		contentPanel = new JPanel();
		titleLabel = new JLabel();
		title = new JTextField();
		workTypeLabel = new JLabel();
		workTypeCombo = new JComboBox(workTypesComboBoxModel);
		workTypesBtn = new JButton();
		projectLabel = new JLabel();
		projectCombo = new JComboBox(projectsComboBoxModel);
		projectsBtn = new JButton();
		startTimeLabel = new JLabel();
		startTime = new JTextField();
		finishTimeLabel = new JLabel();
		finishTime = new JTextField();
		finishNowBtn = new JButton();
		commentsLlabel = new JLabel();
		scrollPane1 = new JScrollPane();
		comments = new JTextArea();
		buttonBar = new JPanel();
		saveButton = new JButton();
		cancelButton = new JButton();
		saveAction = new SaveAction();
		cancelAction = new CancelAction();
		workTypesDialogAction = new WorkTypesDialogAction();
		projectsDialogAction = new ProjectsDialogAction();
		finishNowAction = new FinishNowAction();

		//======== this ========
		setTitle(bundle.getString("ActivityDialog.Title"));
		setModal(true);
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== dialogPane ========
		{
			dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));

			// JFormDesigner evaluation mark
			dialogPane.setBorder(new javax.swing.border.CompoundBorder(
				new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
					"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
					javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
					java.awt.Color.red), dialogPane.getBorder())); dialogPane.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});

			dialogPane.setLayout(new BorderLayout());

			//======== contentPanel ========
			{
				contentPanel.setLayout(new GridBagLayout());
				((GridBagLayout)contentPanel.getLayout()).columnWidths = new int[] {0, 135, 47, 46, 39};
				((GridBagLayout)contentPanel.getLayout()).rowHeights = new int[] {0, 0, 0, 0, 0, 61};
				((GridBagLayout)contentPanel.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 1.0, 0.0};
				((GridBagLayout)contentPanel.getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 1.0};

				//---- titleLabel ----
				titleLabel.setText(bundle.getString("Activity.Title.Title"));
				contentPanel.add(titleLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));
				contentPanel.add(title, new GridBagConstraints(1, 0, 4, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 0), 0, 0));

				//---- workTypeLabel ----
				workTypeLabel.setText(bundle.getString("Activity.WorkType.Title"));
				contentPanel.add(workTypeLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));
				contentPanel.add(workTypeCombo, new GridBagConstraints(1, 1, 3, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));

				//---- workTypesBtn ----
				workTypesBtn.setText("...");
				workTypesBtn.setAction(workTypesDialogAction);
				contentPanel.add(workTypesBtn, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 0), 0, 0));

				//---- projectLabel ----
				projectLabel.setText(bundle.getString("Activity.Project.Title"));
				contentPanel.add(projectLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));
				contentPanel.add(projectCombo, new GridBagConstraints(1, 2, 3, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));

				//---- projectsBtn ----
				projectsBtn.setText("...");
				projectsBtn.setAction(projectsDialogAction);
				contentPanel.add(projectsBtn, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 0), 0, 0));

				//---- startTimeLabel ----
				startTimeLabel.setText(bundle.getString("Activity.StartTime.Title"));
				contentPanel.add(startTimeLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));
				contentPanel.add(startTime, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));

				//---- finishTimeLabel ----
				finishTimeLabel.setText(bundle.getString("Activity.FinishTime.Title"));
				contentPanel.add(finishTimeLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));
				contentPanel.add(finishTime, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));

				//---- finishNowBtn ----
				finishNowBtn.setText(bundle.getString("ActivityDialog.FinishNowBtn.Text"));
				finishNowBtn.setAction(finishNowAction);
				contentPanel.add(finishNowBtn, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 5, 5), 0, 0));

				//---- commentsLlabel ----
				commentsLlabel.setText(bundle.getString("Activity.Comments.Title"));
				contentPanel.add(commentsLlabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0,
					GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
					new Insets(0, 0, 0, 5), 0, 0));

				//======== scrollPane1 ========
				{
					scrollPane1.setViewportView(comments);
				}
				contentPanel.add(scrollPane1, new GridBagConstraints(1, 5, 4, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 0, 0), 0, 0));
			}
			dialogPane.add(contentPanel, BorderLayout.CENTER);

			//======== buttonBar ========
			{
				buttonBar.setBorder(new EmptyBorder(12, 0, 0, 0));
				buttonBar.setLayout(new GridBagLayout());
				((GridBagLayout)buttonBar.getLayout()).columnWidths = new int[] {0, 85, 80};
				((GridBagLayout)buttonBar.getLayout()).columnWeights = new double[] {1.0, 0.0, 0.0};

				//---- saveButton ----
				saveButton.setText(bundle.getString("Save"));
				saveButton.setAction(saveAction);
				buttonBar.add(saveButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 0, 5), 0, 0));

				//---- cancelButton ----
				cancelButton.setText(bundle.getString("Cancel"));
				cancelButton.setAction(cancelAction);
				buttonBar.add(cancelButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
					GridBagConstraints.CENTER, GridBagConstraints.BOTH,
					new Insets(0, 0, 0, 0), 0, 0));
			}
			dialogPane.add(buttonBar, BorderLayout.SOUTH);
		}
		contentPane.add(dialogPane, BorderLayout.CENTER);
		pack();
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Ivan Latysh
	private JPanel dialogPane;
	private JPanel contentPanel;
	private JLabel titleLabel;
	private JTextField title;
	private JLabel workTypeLabel;
	private JComboBox workTypeCombo;
	private JButton workTypesBtn;
	private JLabel projectLabel;
	private JComboBox projectCombo;
	private JButton projectsBtn;
	private JLabel startTimeLabel;
	private JTextField startTime;
	private JLabel finishTimeLabel;
	private JTextField finishTime;
	private JButton finishNowBtn;
	private JLabel commentsLlabel;
	private JScrollPane scrollPane1;
	private JTextArea comments;
	private JPanel buttonBar;
	private JButton saveButton;
	private JButton cancelButton;
	private SaveAction saveAction;
	private CancelAction cancelAction;
	private WorkTypesDialogAction workTypesDialogAction;
	private ProjectsDialogAction projectsDialogAction;
	private FinishNowAction finishNowAction;
	// JFormDesigner - End of variables declaration  //GEN-END:variables

	private class SaveAction extends AbstractAction {
		private SaveAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("Save"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      String _date = dateFormat.format(date);
      // update action
      action = "save";
      // update title
      activity.setTitle(title.getText());
      // update work type
      Object selectedWorkType = workTypesComboBoxModel.getSelectedItem();
      if (null!= selectedWorkType) activity.setWorkTypeCode(((WorkType)selectedWorkType).getCode());
      // update project
      Object selectedProject = projectsComboBoxModel.getSelectedItem();
      if (null!= selectedProject) activity.setProjectCode(((Project)selectedProject).getCode());

      try {
        if (startTime.getText().trim().length()>0) {
          activity.setStartTime(time2DateFormat.parse(_date+startTime.getText()));
        }
      } catch (ParseException ex) {
        logger.error("Unable to parse start time {"+startTime.getText()+"}", ex);
      }
      try {
        if (finishTime.getText().trim().length()>0) {
          activity.setFinishTime(time2DateFormat.parse(_date+finishTime.getText()));
        }
      } catch (ParseException ex) {
        logger.error("Unable to parse finish time {"+finishTime.getText()+"}", ex);
      }
      activity.setComments(comments.getText());
      // close dialog
      setVisible(false);
		}
	}

	private class CancelAction extends AbstractAction {
		private CancelAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("Cancel"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
			ActivityDialog.this.setVisible(false);
		}
	}

	private class WorkTypesDialogAction extends AbstractAction {
		private WorkTypesDialogAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			putValue(NAME, "...");
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      // create a Work Types dialog
      WorkTypesDialog dialog = new WorkTypesDialog(ActivityDialog.this);
      // display dialog
      dialog.setVisible(true);
      // dispose dialog
      dialog.dispose();
		}
	}

	private class ProjectsDialogAction extends AbstractAction {
		private ProjectsDialogAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			putValue(NAME, "...");
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      // create a projects dialog
      ProjectsDialog dialog = new ProjectsDialog(ActivityDialog.this);
      // display dialog
      dialog.setVisible(true);
      // dispose dialog
      dialog.dispose();
		}
	}

	private class FinishNowAction extends AbstractAction {
		private FinishNowAction() {
			// JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
			// Generated using JFormDesigner Evaluation license - Ivan Latysh
			ResourceBundle bundle = ResourceBundle.getBundle("org.timeticker.timeticker");

			putValue(NAME, bundle.getString("ActivityDialog.FinishNowBtn.Text"));
			// JFormDesigner - End of action initialization  //GEN-END:initComponents
		}

		public void actionPerformed(ActionEvent e) {
      activity.setFinishTime(new Date());
      finishTime.setText(date2TimeFormat.format(activity.getFinishTime()));
		}
	}
}
